package com.formula.datastructure.standard.list;

import com.formula.datastructure.util.DataUtil;

public class SentiLinkedList {

    // 如果没有Head, 那么从何开始CRUD, 但是head从来不暴露给外面
    // java没有指针概念, 所以如果head本身不存放内容，就是头结点
    private LinkedNode head;

    private int size;

    public SentiLinkedList() {
        head = new LinkedNode(null);
        // java没有指针，若head不存放值，其实就是头结点
        head.next = null;
    }

    public int getSize() {
        return size;
    }

    public void printAll() {
        LinkedNode temp = head;
        while (temp.next != null) {
            System.out.println(temp.next.data);
            temp = temp.next;
        }
    }

    public void add(Integer input) {
        LinkedNode newNode = new LinkedNode(input);
        if (head.next != null) {
            newNode.next = head.next;
        }
        head.next = newNode;
        size++;
    }

    public void delete(Integer input) {
        if (head.next == null) {
            System.out.println("List is empty.");
        } else {
            LinkedNode parentNode = head;
            while (parentNode.next != null) {
                if (parentNode.next.data.equals(input)) {
                    break;
                } else {
                    parentNode = parentNode.next;
                }
            }
            if (parentNode.next != null) {
                parentNode.next = parentNode.next.next;
                size--;
            } else {
                System.out.println("No found.");
            }
        }
    }

    public boolean findByValue(Integer value) {
        LinkedNode parentNode = head;
        while (parentNode.next != null) {
            if (parentNode.next.data.equals(value)) {
                System.out.println(value + " is found.");
                return true;
            } else {
                parentNode = parentNode.next;
            }
        }
        return false;
    }

    public void update(Integer orig, Integer newValue) {

    }

    public static void main(String[] args) {
        SentiLinkedList list = new SentiLinkedList();
        Integer[] array = DataUtil.genUniqueArray(12, 20);
        DataUtil.printArray(array);
        for (int i = 0; i < 12; i++) {
            list.add(array[i]);
        }
        System.out.println(list.size);
        list.findByValue(3);
        list.findByValue(7);
        list.delete(3);
        list.delete(7);
        System.out.println(list.size);
        list.printAll();
    }
}
